package com.globallogic.socialnetwork.service;

import javax.annotation.Resource;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.interceptor.Interceptors;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageListener;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor;

import com.globallogic.socialnetwork.dao.UserDao;
import com.globallogic.socialnetwork.entity.User;
import com.globallogic.socialnetwork.util.DaoException;


/**
 * Implementation of the Service Layer.
 */
@MessageDriven(mappedName = "jms/Queue-0")
@Interceptors(SpringBeanAutowiringInterceptor.class)
public class MessageService implements MessageListener {
	@Resource
	private MessageDrivenContext mdc;

	@Autowired
	private UserDao userDao;
	
	private final static Logger log = Logger
			.getLogger("SocialNetworkFileLogger");

	public MessageService() {
	}
 
	
	
	/**
	 * This methods acts when MessageService catches send method to JMS.
	 * Turns message to MapMessage and gets <sender>,<receiver> and <message> from there
	 * and calls sendMessage method.
	 */
	@Override
	public void onMessage(javax.jms.Message message) {
		final MapMessage mm = (MapMessage) message;
		try {
			String sender = mm.getString("sender");
			String receiver = mm.getString("receiver");
			String messageText = mm.getString("message");
			sendMessage(sender, receiver, messageText);
		} catch (JMSException e) {
			log.error(e);
		}
	}

	/**
	 * Send message to <receiver> with content <message>
	 * 
	 * @return "home?faces-redirect=true"
	 */
	public void sendMessage(String sender, String receiver, String message) {

		try {
			if (!receiver.isEmpty() && !message.isEmpty()) {
				User senderUser = userDao.getUserByLogin(sender);
				User receiverUser = userDao.getUserByLogin(receiver);
				userDao.sendMessage(senderUser, receiverUser, message);
				log.warn("Sending message: " + message + " to " + receiver);
			}
		} catch (DaoException e) {
			log.warn(e);
		}
	 
	}

	public void setUserDao(UserDao userDao) {

	}

	public UserDao getUserDao() {
		return userDao;
	}

}